﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using System;
using System.Security.Cryptography;
using QxFramework.Core;
using QxFramework.Utilities;

namespace QxFramework.Core
{
    /// <summary>
    /// 资源管理，提供各项本地资源，包括物体对象和UI等的解码和加载功能。
    /// </summary>
    public class ResourceManager : Singleton<ResourceManager>, ISystemModule
    {
        /// <summary>
        /// 存储已加载的资源的字典
        /// </summary>
        private Dictionary<string, UnityEngine.Object> _cache = new Dictionary<string, UnityEngine.Object>();

        /// <summary>
        /// 存储已加载的资源的数组的字典
        /// </summary>
        private Dictionary<string, UnityEngine.Object[]> _arrayCache = new Dictionary<string, UnityEngine.Object[]>();

        /// <summary>
        /// 存储要进行内存清理的资源的字典
        /// </summary>
        private Dictionary<string, UnityEngine.Object> _cacheClearable = new Dictionary<string, UnityEngine.Object>();

        /// <summary>
        /// 存储正在加载的资源
        /// </summary>
        private List<AsyncObjectInfo> _loadingObjList = new List<AsyncObjectInfo>();

        /// <summary>
        /// 对象池默认大小
        /// </summary>
        private int ObjectPoolDefaultCount = 3;
        

        /// <summary>
        /// 持久化的文件存储URL，直接读取
        /// </summary>
        /// <returns></returns>
        public string PersistentDataUrl
        {
            get
            {
                return "file:///" + Application.persistentDataPath + "/";
                
            }
        }

        /// <summary>
        /// Loads the specified path.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path">The path.</param>
        /// <param name="instance">if set to <c>true</c> [instance].</param>
        /// <returns></returns>
        public T Load<T>(string path, bool instance = false) where T : UnityEngine.Object
        {
            T asset;
            if(_cache.ContainsKey(path))
            {
                asset = _cache[path] as T;
            }
            else if(_cacheClearable.ContainsKey(path))
            {
                asset = _cacheClearable[path] as T;
            }
            else
            {
                asset = Resources.Load<T>(path) as T;
                _cache[path] = asset;
            }

            if(asset != null && instance)
            {
                return UnityEngine.Object.Instantiate(asset);
            }
            if(asset == null)
            {
                Debug.LogError("加载资源Path没有加载到:"+path);
            }
            return asset;
        }


        public T[] LoadAll<T>(string path) where T : UnityEngine.Object
        {
            if(_arrayCache.ContainsKey(path))
            {
                return _arrayCache[path] as T[];
            }
            else
            {
                var t = Resources.LoadAll<T>(path);
                _arrayCache[path] = t;
                for(int i = 0 ; i < t.Length ; i++)
                {
                    _cache[path + "/" + t[i].name] = t[i];
                }
                return t;
            }
        }

        public Dictionary<string,T> LoadAllToDic<T>(string path) where T:UnityEngine.Object
        {
            Dictionary<string, T> newDic = new Dictionary<string, T>();
            if (_arrayCache.ContainsKey(path))
            {
                foreach(T obj in _arrayCache[path])
                {
                    newDic.Add(obj.name,obj);
                }
                return newDic;
            }
            else
            {
                var t = Resources.LoadAll<T>(path);
                _arrayCache[path] = t;
                for (int i = 0; i < t.Length; i++)
                {
                    _cache[path + "/" + t[i].name] = t[i];
                }
                foreach (T obj in t)
                {
                    newDic.Add(obj.name, obj);
                }
                return newDic;
            }
            

        }

        /// <summary>
        /// 专用于Load要进行内存清理的资源
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <param name="instance"></param>
        /// <returns></returns>
        public T LoadClearable<T>(string path, bool instance = false) where T : UnityEngine.Object
        {
            T asset;
            if(_cacheClearable.ContainsKey(path))
            {
                asset = _cacheClearable[path] as T;
            }
            else
            {
                asset = Resources.Load<T>(path) as T;
                _cacheClearable[path] = asset;
            }

            if(asset != null && instance)
            {
                return UnityEngine.Object.Instantiate(asset);
            }
            return asset;
        }

        public void ClearCache()
        {
            _cacheClearable.Clear();
            Resources.UnloadUnusedAssets();
            GC.Collect();
        }
        
        /// <summary>
        /// 异步加载资源，把正在进行加载的资源存进_loadingObjList
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <param name="clearable"></param>
        /// <param name="area"></param>
        public void LoadAsync<T>(string path,bool clearable,string area="") where T : UnityEngine.Object
        {
            AsyncObjectInfo asycnObjectInfo = new AsyncObjectInfo(path, Resources.LoadAsync<T>(path), clearable,area);
            _loadingObjList.Add(asycnObjectInfo);
        }

        public bool CheckLoadingObj()
        {
            bool isComplete = true;
            for(int i = _loadingObjList.Count-1 ; i>=0 ;i--)
            {
                if(_loadingObjList[i].ResourceRequest.isDone)
                {
                    if(_loadingObjList[i].Clearable)
                    {
                        _cacheClearable.Add(_loadingObjList[i].Path, _loadingObjList[i].ResourceRequest.asset);
                    }
                    else
                    {
                        _cache.Add(_loadingObjList[i].Path, _loadingObjList[i].ResourceRequest.asset);
                    }
                    _loadingObjList.RemoveAt(i);
                }
                else
                {
                    isComplete = false;
                }
            }
            return isComplete;
        }

        /// <summary>
        /// 从文件中实例化预设到游戏物体。
        /// </summary>
        /// <param name="path">预设目录。</param>
        /// <param name="parent">设置的父对象。</param>
        /// <returns></returns>
        public GameObject Instantiate(string path, Transform parent = null)
        {
            GameObject asset = Load<GameObject>(path);
            GameObject go = null;
            if (asset != null)
            {
                go = GameObject.Instantiate(asset, parent) as GameObject;
            }
            return go;
        }

        public GameObject Instantiate(GameObject asset,Transform parent = null)
        {
            GameObject go = null;
            if (asset != null)
            {
                go = GameObject.Instantiate(asset, parent) as GameObject;
            }
            return go;
        }

        public GameObject Instantiate(GameObject asset,Vector3 pos, Transform parent = null)
        {
            GameObject go = null;
            if (asset != null)
            {
                go = GameObject.Instantiate(asset,pos, Quaternion.identity) as GameObject;
                go.transform.SetParent(parent);
            }
            return go;
        }

        public GameObject InstantiateWithPool(GameObject asset, Vector3 pos, Transform parent = null)
        {
            if (ObjectPoolExtensions.IsExistPool(asset) == false)
            {
                ObjectPoolExtensions.CreatePool(asset,ObjectPoolDefaultCount);
                if (parent == null)
                {
                    return ObjectPoolExtensions.Spawn(asset, pos);
                }
                else
                {
                    return ObjectPoolExtensions.Spawn(asset, parent, pos);
                }
               
            }
            else
            {
                if (parent == null)
                {
                    return ObjectPoolExtensions.Spawn(asset, pos);
                }
                else
                {
                    return ObjectPoolExtensions.Spawn(asset, parent, pos);
                }
            }
        }

        public void DestroyGameObject(GameObject asset, float time = 0)
        {
            if (ObjectPoolExtensions.IsExistPool(asset) == false)
            {
                UnityEngine.GameObject.Destroy(asset,time);
            }
            else
            {
                ObjectPoolExtensions.Recycle(asset,time);
            }
        }

        public void Update(float deltaTime)
        {
        }

        public void FixedUpdate(float deltaTime)
        {
        }

        public void Dispose()
        {
        }

        /// <summary>
        /// 测试目录是否有写权限
        /// </summary>
        /// <param name="folderPath">路径</param>
        /// <returns>有写权限</returns>
        public static bool HasWriteAccessToFolder(string folderPath)
        {
            try
            {
                string tmpFilePath = Path.Combine(folderPath, Path.GetRandomFileName());
                using (
                    FileStream fs = new FileStream(tmpFilePath, FileMode.CreateNew, FileAccess.ReadWrite,
                        FileShare.ReadWrite))
                {
                    StreamWriter writer = new StreamWriter(fs);
                    writer.Write("1");
                }
                File.Delete(tmpFilePath);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public bool InCache(string path)
        {
            return (_cache.ContainsKey(path));
        }

        public void AddCache(string path, UnityEngine.Object obj)
        {
            _cache.Add(path, obj);
        }
    }
    class AsyncObjectInfo
    {
        public string Path;
        public bool Clearable;
        public ResourceRequest ResourceRequest;
        public string Area;
        public AsyncObjectInfo(string path, ResourceRequest resourceRequest, bool clearable,string area)
        {
            this.Path = path;
            this.ResourceRequest = resourceRequest;
            this.Clearable = clearable;
            this.Area = area;
        }
    }

}